<script setup lang="ts">
import {
  getPatientInfoByIdAPI,
  postPatientAddAPI,
  putPatientUpdateAPI,
} from "@/apis/patient";
import type { PostPatientAddParams } from "@/types/patient";
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue";

// 1. 收集表单数据
const formData = ref<PostPatientAddParams>({
  name: "",
  idCard: "",
  defaultFlag: 0,
  gender: 1,
});
// 2. 定义校验规则
const formRules = ref<UniHelper.UniFormsRules>({
  name: {
    rules: [
      { required: true, errorMessage: "请填写患者姓名" },
      {
        pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/,
        errorMessage: "请输入中文姓名",
      },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: "请填写患者身份证号" },
      {
        pattern:
          /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
        errorMessage: "请输入正确的身份证号",
      },
    ],
  },
  gender: {
    rules: [
      { required: true, errorMessage: "请勾选患者性别" },
      {
        // 自定义校验规则
        validateFunction: (rule, value, data, callback) => {
          // 获取身份证号第17位
          const idCardGenderNumber = formData.value.idCard.charAt(16);
          // 判断身份证号第17位是否与选择的性别不一致
          if (Number(idCardGenderNumber) % 2 !== value) {
            callback("选择的性别与身份号中性别不一致");
          }
          // 验证通过返回 true
          return true;
        },
      },
    ],
  },
});
// 3. 校验表单和提交表单
const formRef = ref<UniHelper.UniFormsInstance>();
const onSubmit = async () => {
  // 校验表单
  await formRef.value?.validate?.();
  // 如果页面参数有 id，调用编辑接口，否则调用添加接口
  if (props.id) {
    const { name, idCard, defaultFlag, id, gender } = formData.value;
    //编辑患者
    await putPatientUpdateAPI({ name, idCard, defaultFlag, id, gender });
  } else {
    // 调用接口，注意：一个帐号最多添加 6 个患者
    await postPatientAddAPI(formData.value);
  }
  uni.navigateBack();
  // 提示用户
  uni.showToast({ title: "保存成功", icon: "success" });
};

// 4. Switch 开关组件切换事件
const onChangeDefaultFlag = (event: UniHelper.SwitchOnChangeEvent) => {
  formData.value.defaultFlag = event.detail.value ? 1 : 0;
};

// 5. 接收页面参写法2-更方便
const props = defineProps<{ id?: string }>();
console.log("页面级组件，可通过 props 接收页面参数", props);
// 动态设置导航栏标题
uni.setNavigationBarTitle({ title: props.id ? "编辑患者" : "添加患者" });

const getPatientInfoById = async () => {
  // 如果 props.id 存在，则查询患者详情
  console.log("id", props.id);

  if (props.id) {
    // 根据患者id获取详情
    const res = await getPatientInfoByIdAPI(props.id);
    // 保存患者信息，在表单中回显
    formData.value = res.data;
  }
};
getPatientInfoById();
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms
        border
        label-width="220rpx"
        ref="formRef"
        :model="formData"
        :rules="formRules"
      >
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch
              :checked="formData.defaultFlag === 1"
              @change="onChangeDefaultFlag"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @tap="onSubmit">保存</button>
      </uni-forms>
      {{ formData }}
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import "./index.scss";
</style>
